const service = require('../service');
const Utils = require('../utils');

class Home {

  async putSong(req, res) {
    const {
      songName = ''
    } = req.body;
    let result = {
      code: -1
    };
    try {
      const song = await service.music.searchSong(
        songName.replace('@liwei ', '')
      );
      if (!song) {
        res.send(result);
        return;
      }
      await service.music_plat.addSong(song, req, {
        repeat: songName.indexOf('@liwei ') !== -1
      });
      result.code = 200;
    } catch (error) {
      Utils.Logger.error(error.stack);
      result.code = 500;
    }
    res.send(result)
      .end();
  }

  getSongList(req, res) {
    let result = {
      code: -1
    };
    try {
      const songs = service.music_plat.getSongs();
      result = {
        code: 200,
        data: songs
      };
    } catch (error) {
      Utils.Logger.error(error.stack);
      result.code = 500;
    }
    res.send(result)
      .end();
  }

  async getCurrentSong(req, res) {
    let result = {
      code: -1
    };
    try {
      const song = service.music_plat.getFirstSong();
      if (!song) {
        res.send(result);
        return;
      }
      result = {
        code: 200,
        data: song.song
      };
    } catch (error) {
      Utils.Logger.error(error.stack);
      result.code = 500;
    }
    res.send(result)
      .end();
  }

  upgrade(req, res) {
    try {
      const ip = Utils.Func.getIP(req);
      service.websocket.ws.handleUpgrade(
        req,
        req.socket,
        req.headers,
        ws => {
          ws.ID = ip;
          service.websocket.ws.emit(
            'connection',
            ws
          );
        }
      );
    } catch (error) {
      Utils.Logger.error(error.stack);
      res.end();
    }
  }

  async nextSong(req, res) {
    let result = {
      code: -1
    };
    try {
      const ip = Utils.Func.getIP(req);
      const change = service.music_plat.next(ip);
      if (!change) {
        res.send(result);
        return;
      }
      service.websocket.userChangeSong({
        from: ip
      });
      result.code = 200;
    } catch (error) {
      Utils.Logger.error(error.stack);
      result.code = 500;
    }
    res.send(result)
      .end();
  }

  async test(req, res) {
    const r = await service.music.searchSong('红装')
    console.log(r)
    res.end('00')
  }

}


module.exports = new Home();